<?php
class qMySQLFactory
{
    private static $links = array();
    
    public static function MySQLConnect($host, $user, $pass, $db = null)
    {
    	// LOG: Connecting...
    	$link = new qMySQLConnection($host, $user, $pass);    
    	 
    	if ($error = $link->Error())
    	{
    	    // LOG: Error: $error...
    	    unset($link);
    		return false;
    	}
    	// LOG: Connected.
    	
    	if ($db != null)
    	{
    	    // LOG: Selecting database...
    	    $link->SelectDatabase($db);
    	    
    	    if ($error = $link->Error())
    	    {
    	        // LOG: Error: $error...
    	        unset($link);
    	        return false;
    	    }
    	    // LOG: Database selected.
    	}
    	
    	self::$links[] = $link;
    	return array_search($link, self::$links);
    }
    
    public static function MySQLClose($linkid)
    {
    	if (!array_key_exists($linkid, self::$links))
    	{
    	    // LOG: Error: trying to close unexisting connection with ID $linkid
    	    return false;
    	}
    	
        // LOG: Disconnecting...
        self::{$linkid}->Disconnect;
        
        if ($error = self::{$linkid}->Error())
        {
            // LOG: Error when closing connection: $error
            return false;
        }
        // LOG: Connection closed.
        
        unset(self::$links[$linkid]);
        return true;
    }
    
    public static function GetLink($id)
    {
        return self::{$id};
    }
    
    public static function __get($id)
    {
        if (!array_key_exists($id, self::$links))
        {
            // LOG: Error: trying to get unexisting connection
            return false;
        }
        
        return self::$links[$id];
    }
}